<template>
  <div>
    <el-button
      type="primary"
      icon="el-icon-plus"
      style="margin: 10px 0px"
      @click.native="addTradeMarke"
      >添加品牌</el-button
    >
    <el-table style="width: 100%" border :data="list">
      <el-table-column type="index" label="序号" width="80px" align="center">
      </el-table-column>
      <el-table-column prop="tmName" label="品牌名称" width="width">
      </el-table-column
      ><el-table-column prop="prop" label="品牌logo" width="width">
        <template v-slot="{ row, $index }">
          <img :src="row.logoUrl" alt="" style="width: 100px; height: 100px" />
        </template>
      </el-table-column>
      <el-table-column prop="prop" label="操作" width="width">
        <template v-slot="{ row, $index }">
          <el-button
            type="warning"
            icon="el-icon-edit"
            size="mini"
            @click="UpdataTradeMarke(row)"
            >修改</el-button
          >
          <el-button
            type="danger"
            icon="el-icon-delete"
            size="mini"
            @click="DeleteRradeMark(row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <!-- @size-change="handleSizeChange"
      @current-change="handleCurrentChange" -->
    <!-- 添加分页器组件 -->
    <el-pagination
      @current-change="handleCurrentChange"
      @size-change="handleSizeChange"
      style="margin-top: 20px; text-align: center"
      :current-page="page"
      :page-sizes="[3, 5, 10]"
      :page-size="limit"
      layout="prev, pager, next, jumper,->,sizes,total "
      :total="total"
    >
    </el-pagination>
    <!-- 添加品牌或者是修改品牌弹出框 -->
    <el-dialog
      :title="tmFrom.id ? '修改品牌' : '添加品牌'"
      :visible.sync="dialogFormVisible"
    >
      <el-form style="width: 80%" :model="tmFrom" :rules="rules" ref="ruleForm">
        <!-- :model="tmFrom"收集我们输入的表单数据,发送给elementUI服务器，将来的表单验证也需要这个属性 -->
        <el-form-item label="品牌名称" label-width="100px" prop="tmName">
          <el-input autocomplete="off" v-model="tmFrom.tmName"></el-input>
        </el-form-item>
        <el-form-item label="品牌LOGO" label-width="100px" prop="logoUrl">
          <!-- //!!action="/dev-api/admin/product/upload" 图片上传的地址，这是elementUI已经写好了上传API函数 自己写好地址就行 -->
          <el-upload
            class="avatar-uploader"
            action="/dev-api/admin/product/upload"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="tmFrom.logoUrl" :src="tmFrom.logoUrl" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            <div slot="tip" class="el-upload__tip">
              只能上传jpg/png文件，且不超过500kb
            </div>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="addOrUpdataTradeMark"
          >确 定</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "tradeMark",
  //自定义表单验证规则
  data() {
    var validateFrom = (rule, value, callback) => {
      if (value.length < 2 || value.length > 10) {
        callback(new Error("品牌名称2-10位"));
      } else {
        callback();
      }
    };
    return {
      page: 1,
      limit: 3,
      total: 0,
      list: [],
      dialogFormVisible: false,
      //收集品牌的信息，发送给服务器的数据
      //看api文档来命名数据
      tmFrom: {
        logoUrl: "",
        tmName: "",
      },
      rules: {
        tmName: [
          { required: true, message: "请输入活动名称", trigger: "blur" },
          //使用自定义的表单验证规则
          { validator: validateFrom, trigger: "change" },
        ],
        logoUrl: [{ required: true, message: "请选择品牌照片" }],
      },
    };
  },
  mounted() {
    this.getPageList();
  },
  methods: {
    async getPageList() {
      const { page, limit } = this;
      let result = await this.$API.trademark.reqTradeMarkList(page, limit);
      // console.log(result, "获得品牌数据");
      if (result.code == 200) {
        this.total = result.data.total;
        this.list = result.data.records;
      }
    },
    //得到当前页码  这里是自定义事件
    handleCurrentChange(pager) {
      this.page = pager;
      this.getPageList();
    },
    //改变页面显示的类容的条数
    handleSizeChange(limiter) {
      this.limit = limiter;
      this.getPageList();
    },
    //上传图片相关的回调
    //!!这一步最最主要目的:拿到logoUrl的具体信息(其他地方没法拿到logoUrl信息) 然后想我们自己的服务器发送请求（向服务器传参需要logoUrl的信息）
    handleAvatarSuccess(res, file) {
      console.log(res, "上传成功后返回前端的数据");
      this.tmFrom.logoUrl = res.data;
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
    //添加一个品牌按钮
    addTradeMarke() {
      this.dialogFormVisible = true;
      this.tmFrom = { tmMame: "", logoUrl: "" };
    },
    //修改品牌按钮
    UpdataTradeMarke(row) {
      this.dialogFormVisible = true;
      console.log(row, "作用域插槽返回过的数据");
      //!!这里实现的是浅拷贝（第一层来说是深拷贝）！！！！  新输入的row数据，不会影响this.tmFrom
      this.tmFrom = { ...row };
    },
    //添加品牌或者修改品牌到数据库后端
    addOrUpdataTradeMark() {
      //进行表单验证
      console.log(this.$refs.ruleForm);
      this.$refs.ruleForm.validate(async (success) => {
        if (success) {
          this.dialogFormVisible = false;
          let result = await this.$API.trademark.reqAddOrEditTrademark(
            this.tmFrom
          );
          // console.log(result);
          if (result.code == 200) {
            this.$message({
              message: this.tmFrom.id ? "修改成功" : "添加成功",
              type: "success",
            });
            this.getPageList();
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    //删除品牌
    DeleteRradeMark(row) {
      this.$confirm(`此操作将永久删除${row.tmName}, 是否继续?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          let result = await this.$API.trademark.reqDeleteTradeMark(row.id);
          // console.log(result, "删除请求");
          if (result.code == 200) {
            this.$message({
              type: "success",
              message: "删除成功!",
            });
            this.getPageList();
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
  },
};
</script>

<style >
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>